package scau.erps.view.base;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import scau.erps.app.Erps;
import scau.erps.entity.Product;
import scau.erps.entity.Sand;
import scau.erps.entity.TeamOrder;
import scau.erps.service.ProductService;
import scau.erps.service.SandService;
import scau.erps.service.TeamOrderService;
import scau.erps.service.impl.ProductServiceImpl;
import scau.erps.service.impl.SandServiceImpl;
import scau.erps.service.impl.TeamOrderServiceImpl;
import scau.erps.util.CalculateQuarter;

/**
 * 交货面板
 * @author FYJ
 * 
 */
public class DeliveryPanel extends JPanel implements ActionListener {
	private static final long serialVersionUID = 1L;
	protected JComboBox<String> teamCombo;
	protected JButton searchBtn, operationBtn1, operationBtn2, operationBtn3,
			operationBtn4, operationBtn5;
	protected JPanel contentPanel, actionPanel;
	protected JScrollPane dataPanel;
	protected JTable table;
	protected DefaultTableCellRenderer render;
	private OrderTableModel dataModel;
	private DecisionPanel superPanel;
	final int team_Id = Erps.getCurrentTeam().getId();
	TeamOrderService teamOrderService = Erps.getIocInstance().get(
			TeamOrderServiceImpl.class);
	ProductService productService = Erps.getIocInstance().get(
			ProductServiceImpl.class);
	SandService sandService = Erps.getIocInstance().get(SandServiceImpl.class);

	public DeliveryPanel(DecisionPanel superPanel) {
		this.superPanel=superPanel;
		teamCombo = new JComboBox<String>(new String[] { "产品名称", "Beryl",
				"Crystal", "Ruby", "Sapphire" });
		searchBtn = new JButton("筛选");
		operationBtn1 = new JButton("交货");
		operationBtn2 = new JButton("延迟交货");
		operationBtn3 = new JButton("申请高利贷");
		operationBtn4 = new JButton("查看产品库存");
		operationBtn5 = new JButton("取消订单");
		searchBtn.addActionListener(this);
		operationBtn1.addActionListener(this);
		operationBtn2.addActionListener(this);
		operationBtn3.addActionListener(this);
		operationBtn4.addActionListener(this);
		operationBtn5.addActionListener(this);
		actionPanel = new JPanel(); // 顶部交互操作面板
		actionPanel.add(teamCombo);
		actionPanel.add(searchBtn);
		actionPanel.add(operationBtn1);
		actionPanel.add(operationBtn2);
		actionPanel.add(operationBtn5);
		actionPanel.add(operationBtn4);
		actionPanel.add(operationBtn3);
		table = new JTable();
		dataModel = getOrderTableModel();
		table.setModel(dataModel);
		table.setPreferredScrollableViewportSize(new Dimension(930, 200));
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		dataPanel = new JScrollPane(table);
		dataPanel.setViewportView(table);
		render = new DefaultTableCellRenderer();
		render.setHorizontalAlignment(JLabel.CENTER);
		table.setDefaultRenderer(Object.class, render);
		contentPanel = new JPanel();
		contentPanel.setLayout(new BorderLayout());
		contentPanel.add(actionPanel, BorderLayout.NORTH);
		contentPanel.add(dataPanel, BorderLayout.CENTER);
		this.add(contentPanel);
	}

	private OrderTableModel getOrderTableModel() {
		Sand sand = sandService.getSandByTeam(team_Id);
		String sysTime = sand.getTime();
		List<TeamOrder> list = teamOrderService.getTeamOrderByDeliverTime(
				team_Id, sysTime);
		dataModel = new OrderTableModel(list);
		return dataModel;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == searchBtn) {// 筛选按钮
			String product = null;
			if (teamCombo.getSelectedIndex() != 0) {
				product = (String) teamCombo.getSelectedItem();
			}
			String status = "未交货";
			final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(
					dataModel);
			List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>(
					2);
			if (product != null) {
				filters.add(RowFilter.regexFilter(product));
			}
			if (status != null) {
				filters.add(RowFilter.regexFilter(status));
			}
			sorter.setRowFilter(RowFilter.andFilter(filters));
			this.table.setRowSorter(sorter);
			this.table.setModel(dataModel);
		} else if (e.getSource() == operationBtn1) {// 交货按钮
			int row = this.table.getSelectedRow();

			if (row == -1) {
				JOptionPane.showConfirmDialog(this, "未选中任何行", "提示",
						JOptionPane.CLOSED_OPTION);
			} else {
				int teamOrderId = (int) this.table.getValueAt(row, 0);
				TeamOrder teamOrder = teamOrderService
						.getOrderById(teamOrderId);
				Sand sand = sandService.getSandByTeam(team_Id);
				List<Product> list1 = productService.getProductByTypeAndStatus(
						team_Id, teamOrder.getProduct(), "成品");
				int quantity = teamOrder.getQuantity();
				int cost = 0;
				String pro = teamOrder.getProduct();
				if (teamOrder.getStatus().equals("未交货")) {
					if (quantity <= list1.size()) {// 判断是否有足够的库存交货
						int i = 0;
						for (Product product : list1) {
							cost = cost + product.getCost();
							product.setStatus("已交货");
							productService.updateProduct(product);
							i++;
							if (i == quantity)
								break;
						}
						if (sand.getTime().equals(teamOrder.getReceivable())) {// 判断是否到了收款时间，到了则收款
							teamOrder.setStatus("已收款");
							sand.setCash(sand.getCash() + teamOrder.getTotal()
									- teamOrder.getPenalty());
							sandService.updateSand(sand);
						} else {// 如够产品交货，则交货
							teamOrder.setStatus("已交货");
						}
						teamOrder.setCost(cost);
						teamOrderService.updateTeamOrder(teamOrder);
						int payment = CalculateQuarter.getQuarter(teamOrder.getReceivable(),sand.getTime());						
						JOptionPane.showConfirmDialog(this, "订单交货成功" + "\n"+"应收款账期:"+payment+"\n"
								+ "收款时间" + teamOrder.getReceivable(), "提示",
								JOptionPane.CLOSED_OPTION);
						dataModel = getOrderTableModel();
						this.table.setModel(dataModel);
					} else {
						JOptionPane.showConfirmDialog(this, pro
								+ "产品不足，无法交货，请延迟交货", "提示",
								JOptionPane.CLOSED_OPTION);
					}
				} else {
					JOptionPane.showConfirmDialog(this, "该订单已处理，不能再操作", "提示",
							JOptionPane.CLOSED_OPTION);
				}
			}
		} else if (e.getSource() == operationBtn2) {// 延迟交货按钮
			int row = this.table.getSelectedRow();
			if (row == -1) {
				JOptionPane.showConfirmDialog(this, "未选中任何行", "提示",
						JOptionPane.CLOSED_OPTION);
			} else {
				int teamOrderId = (int) this.table.getValueAt(row, 0);
				TeamOrder teamOrder = teamOrderService
						.getOrderById(teamOrderId);
				if (teamOrder.getStatus().equals("未交货")) {
					Sand sand = sandService.getSandByTeam(team_Id);
					String pro = teamOrder.getProduct();// 获取产品名字
					int penalty = teamOrder.getPenalty() + teamOrder.getTotal()/ 5;// 计算罚款
					int cash = sand.getCash();
					if (teamOrder.getPenalty() >= teamOrder.getTotal()) {// 罚款大于等于总收益，则立即扣取罚款，并取消订单
						sand.setCash(cash - penalty);
						sandService.updateSand(sand);
						teamOrder.setPenalty(penalty);
						teamOrder.setStatus("已取消");
						teamOrderService.updateTeamOrder(teamOrder);
						JOptionPane.showMessageDialog(null, pro
								+ "产品不足，无法交货,已取消订单，同时支付罚款", "提示",
								JOptionPane.INFORMATION_MESSAGE);
					} else {// 延迟交货
						teamOrder.setPenalty(penalty);// 记录罚款
						int other = sand.getOther();
						sand.setOther(other + penalty);
						String timeDeliver = teamOrder.getDeliver();
						teamOrder.setDeliver(CalculateQuarter
								.addOneQuarter(timeDeliver));// 延迟交货时间
						String timeReceivable = teamOrder.getReceivable();
						teamOrder.setReceivable(CalculateQuarter
								.addOneQuarter(timeReceivable));// 延迟收款时间
						teamOrderService.updateTeamOrder(teamOrder);
						this.table.setModel(getOrderTableModel());
						JOptionPane.showMessageDialog(null, "已延迟一个季度交货" + "\n"
								+ "处罚金：" + (teamOrder.getTotal() / 5) + "\n"
								+ "此订单累积处罚金：" + penalty, "提示",
								JOptionPane.INFORMATION_MESSAGE);
					}
				} else {
					JOptionPane.showConfirmDialog(this, "该订单已处理，不能再操作", "提示",
							JOptionPane.CLOSED_OPTION);
				}
			}
		} else if (e.getSource() == operationBtn3) {// 避免因第四季度无法完成订单，罚款后出现破产的情况
			new UsuriousLoanDialog(superPanel);
		} else if (e.getSource() == operationBtn4) {// 显示各种产品库存
			List<Product> list1 = productService.getProductByTypeAndStatus(
					team_Id, "Beryl", "成品");
			int beryl = 0;
			beryl = list1.size();
			List<Product> list2 = productService.getProductByTypeAndStatus(
					team_Id, "Crystal", "成品");
			int crystal = 0;
			crystal = list2.size();
			List<Product> list3 = productService.getProductByTypeAndStatus(
					team_Id, "Ruby", "成品");
			int ruby = 0;
			ruby = list3.size();
			List<Product> list4 = productService.getProductByTypeAndStatus(
					team_Id, "Sapphire", "成品");
			int sapphire = 0;
			sapphire = list4.size();
			String message = "Beryl:" + beryl + "\n" + "Crystal:" + crystal
					+ "\n" + "Ruby:" + ruby + "\n" + "Crystal:" + sapphire;
			JOptionPane.showMessageDialog(null, message, "提示",
					JOptionPane.INFORMATION_MESSAGE);
		} else if (e.getSource() == operationBtn5) {// 取消订单
			int row = this.table.getSelectedRow();
			if (row == -1) {
				JOptionPane.showConfirmDialog(this, "未选中任何行", "提示",
						JOptionPane.CLOSED_OPTION);
			} else {
				int teamOrderId = (int) this.table.getValueAt(row, 0);
				TeamOrder teamOrder = teamOrderService
						.getOrderById(teamOrderId);
				int penalty = teamOrder.getPenalty() + teamOrder.getTotal() / 5;// 计算罚款
				Sand sand = sandService.getSandByTeam(team_Id);
				int other = sand.getOther();
				int cash = sand.getCash();
				sand.setCash(cash - penalty);
				sand.setOther(other + penalty);
				sandService.updateSand(sand);
				teamOrder.setPenalty(penalty);
				teamOrder.setStatus("已取消");
				teamOrderService.updateTeamOrder(teamOrder);
				JOptionPane.showMessageDialog(null, "成功取消订单" + "\n"
						+ "此订单累积处罚金" + penalty, "提示",
						JOptionPane.INFORMATION_MESSAGE);
			}
		}
	}



}

class OrderTableModel extends AbstractTableModel {
	private static final long serialVersionUID = 1L;
	private String[] title = { "序号", "小组", "产品", "年份", "市场", "数量", "金额", "ISO",
			"订单状态", "罚金" };
	private Object[][] data = null;

	public OrderTableModel(List<TeamOrder> list) {
		data = new Object[list.size()][title.length];
		Iterator<TeamOrder> iter = list.iterator();
		for (int i = 0; i < list.size(); i++) {
			TeamOrder teamOrder = iter.next();
			data[i][0] = teamOrder.getId();
			data[i][1] = "第" + teamOrder.getTeam_Id() + "组";
			data[i][2] = teamOrder.getProduct();
			data[i][3] = teamOrder.getYear();
			data[i][4] = teamOrder.getMarket();
			data[i][5] = teamOrder.getQuantity();
			data[i][6] = teamOrder.getTotal();
			data[i][7] = teamOrder.getIso();
			data[i][8] = teamOrder.getStatus();
			data[i][9] = teamOrder.getPenalty();
		}
	}

	@Override
	public int getRowCount() {
		return this.data.length; // 行数
	}

	@Override
	public int getColumnCount() {
		return this.title.length; // 列数
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		return data[rowIndex][columnIndex]; // 取表格单元格值
	}

	public String getColumnName(int columnIndex) {
		return title[columnIndex]; // 显示标题
	}
}
